package edu.regiscollege.cs312.scheduler;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/** Implements a preemptive RoundRobin Scheduler.
 * 
 * It runs each job at most a 'slide' of time, and it switches to execute the next job. 
 * 
 */
public class RoundRobin extends Scheduler {
	private final long slice;
	private final List<Job> jobs;
	private final Map<Job, Long> finishTime;

	public RoundRobin(long slice) {
		this.slice = slice;
		jobs = new LinkedList<Job>();
		finishTime = new HashMap<Job, Long>();
	}

	@Override
	public boolean addJob(Job job, long arrivalTime) {
		super.addJob(job, arrivalTime);
		jobs.add(job);
		return true;
	}

	@Override
	public Map<Job, Long> getOutput() {
		return finishTime;
	}

	@Override
	public void run(CPU cpu) {
		long currentTime = 0;
		while (!jobs.isEmpty()) {
			for (Job job : jobs) {
				long elapsed = cpu.executeForNSecond(job, slice);
				job.setRemainingTime(job.getRemainingTime() - elapsed);
				currentTime += elapsed;
				if (job.getRemainingTime() == 0) {
					finishTime.put(job, currentTime);
				}
			}
			jobs.removeAll(finishTime.keySet());
		}
	}

}
